import request from '@/utils/request'

// ===== 类型定义 =====
export interface ApiResponse<T = any> {
  code: number
  msg?: string
  data?: T
  dataInfo?: any
}

export interface FileInfo {
  id?: number | string
  name?: string
  path?: string
  size?: number
  type?: string
  createTime?: string
  updateTime?: string
  [key: string]: any
}

export interface UploadResult {
  filePath?: string
  url?: string
  originalName?: string
  [key: string]: any
}

// ===== API 函数 =====
export function listFile(query: Record<string, any>): Promise<ApiResponse<FileInfo[]>> {
  return request({
    url: '/system/file/list',
    method: 'get',
    params: query
  }) as Promise<ApiResponse<FileInfo[]>>
}

export function getFile(id: string | number): Promise<ApiResponse<FileInfo>> {
  return request({
    url: '/system/file/' + id,
    method: 'get'
  }) as Promise<ApiResponse<FileInfo>>
}

export function addFile(data: Partial<FileInfo>): Promise<ApiResponse<any>> {
  return request({
    url: '/system/file',
    method: 'post',
    data
  }) as Promise<ApiResponse<any>>
}

export function updateFile(data: Partial<FileInfo>): Promise<ApiResponse<any>> {
  return request({
    url: '/system/file',
    method: 'put',
    data
  }) as Promise<ApiResponse<any>>
}

export function delFile(id: string | number): Promise<ApiResponse<any>> {
  return request({
    url: '/system/file/' + id,
    method: 'delete'
  }) as Promise<ApiResponse<any>>
}

export function uploadProjectFile(projectId: string | number | null, file: File, config: Record<string, any> = {}): Promise<ApiResponse<UploadResult>> {
  const formData = new FormData()
  if (projectId !== undefined && projectId !== null) {
    formData.append('projectId', String(projectId))
  }
  formData.append('multipartFile', file)
  return request({
    url: '/system/file/uploadProjectFile',
    method: 'post',
    data: formData,
    headers: { 'Content-Type': 'multipart/form-data' },
    ...config
  }) as Promise<ApiResponse<UploadResult>>
}

